// funcs
package maputil

import (
	"fmt"
	"strconv"
)

//将keys和vals合并为一个map
func JoinToMap_Str(keys []string, vals []interface{}) map[string]string {
	size := len(keys)
	if l := len(vals); l < size {
		size = l
	}
	kv := map[string]string{}
	for i := 0; i < size; i++ {
		if v := vals[i]; v != nil {
			kv[keys[i]] = fmt.Sprintf("%v", v)
		}
	}
	return kv
}

//将keys和vals合并为一个map
func JoinToMap(keys []string, vals []interface{}) map[string]interface{} {
	size := len(keys)
	if l := len(vals); l < size {
		size = l
	}
	kv := map[string]interface{}{}
	for i := 0; i < size; i++ {
		kv[keys[i]] = vals[i]
	}
	return kv
}

//从kv中获取key，返回int值、是否含有key、错误信息
func GetInt(kv map[string]interface{}, key string) (int, bool, error) {
	return GetIntWithDefault(kv, key, 0)
}

//从kv中获取key，返回int值、是否含有key、错误信息
func GetIntWithDefault(kv map[string]interface{}, key string, def int) (int, bool, error) {
	v, has := kv[key]
	if !has || v == nil {
		return def, false, nil
	}
	sv := fmt.Sprintf("%v", v)
	if iv, err := strconv.Atoi(sv); err == nil {
		return iv, true, nil
	} else {
		return def, true, fmt.Errorf("无效数据[%s]:%s", sv, err.Error())
	}
}
